package com.sendi.system.action;

 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;

import com.sendi.system.entity.Department;
import com.sendi.system.entity.Functionmoudle;
import com.sendi.system.entity.UserDptRelation;
import com.sendi.system.util.tree.ConTreeData;
import com.sendi.system.util.tree.DepartTreeNode;
import com.sendi.system.util.tree.MoudleTreeNode;
import com.sendi.system.util.tree.TreeHelper;
public class DepartmentAction extends SysAction {
    private Integer  id;
    	
   private String deleterecord;
   private int  clickleafid;
   public String reloadflag="no";
 
   
	private String departcode;
	private String departname;
	private String departtype;
	private Integer parentid;
	private String departarea;
	private String departstatus;
	private String departdesc;
	
	   private String querytype;
	   
	    private String username;
	   private int dptid;
	   private String itemselector;
	   
	public DepartmentAction()
	{
		super();
		data_session_name="DepartmentActionListData";
	}
	
	/*
	 * 列出所有模块树结构
	 */
	public void listdpttree()
	{
	      ArrayList<ConTreeData> children=new ArrayList<ConTreeData>();
	 	  HashMap<String,DepartTreeNode> systemdepttreemap=null;
		  Object mt2=this.getServletContext().getAttribute("sendi_sys_deptment_tree");
		  String userid=this.getUserKeyId();
			if(mt2!=null)
		 	{
		  		systemdepttreemap=(HashMap<String,DepartTreeNode>)mt2;
		  	}
			ArrayList<DepartTreeNode> child=systemdepttreemap.get(this.Treeid+"").dchild;
			for(DepartTreeNode dtn:child)
			{
				if(dtn.isPower(userid))
				{
					
					ConTreeData ct=new ConTreeData();
				  	ct.setId(dtn.getTreeId());
				  	ct.setText(dtn.getText());
				    children.add(ct);
				}
			
		 	}
			
			
			
		   String jsons = JSONArray.fromObject(children).toString();
	    //   System.out.println(jsons);
	       writeResponseText(jsons);
	   
	}
	
	public void reConstructDeptData()
	{
		Session session=this.serviceSupportImp.getDao().getSessionFactory().openSession();
		Object mt=this.getServletContext().getAttribute("sendi_sys_dpttree_info");
		Object mt2=this.getServletContext().getAttribute("sendi_sys_deptment_tree");
	    HashMap<String,Department> systemdeptInf=null;
	    HashMap<String,DepartTreeNode> systemdepttreemap=null;
	 	if(mt!=null&&mt2!=null)
	 	{
	 		 
	 		systemdeptInf=( HashMap<String,Department> )mt;
	 		systemdepttreemap=(HashMap<String,DepartTreeNode>)mt2;
	 		
	 	}
	 	systemdeptInf.clear();
	 	systemdepttreemap.clear();
	 	
	 	 String hql12="from Department ";  
	 	 List datas12=session.createQuery(hql12).list();
	 	 for(Object o12:datas12)
	 	 {
	 		Department dpt=(Department)o12;
	 		systemdeptInf.put(dpt.getId()+"", dpt);
	 		DepartTreeNode dtn=new DepartTreeNode();
	 		dtn.setText(dpt.getDepartname());
	 		dtn.setTreeId(dpt.getId());
	 		dtn.setIsleaf(false);
	 		dtn.setParentId(dpt.getParentid());
	 		dtn.f=dpt;
	 		systemdepttreemap.put(dpt.getId()+"", dtn); 
	 	 }
	// 	 applicationContextHelper.servletContext.setAttribute("sendi_sys_dpttree_info", systemdeptInf);
	 	DepartTreeNode droot=new DepartTreeNode(); 
	 	droot.setIsleaf(false);
	 	droot.setText("设备树");
	 	droot.setTreeId(-1);
	 	droot.setIsroot(true);
	 	systemdepttreemap.put("-1", droot);
	 	
	 	
		 String hql13="from UserDptRelation ";  
	    List datas13=session.createQuery(hql13).list();
	 	HashMap<String,ArrayList<String>> userids=new HashMap<String, ArrayList<String>>();
	 	 for(Object o13:datas13)
	 	 {
	 		UserDptRelation udrl=(UserDptRelation)o13;
	 		ArrayList<String> userid=userids.get(udrl.getDptid()+"");
	 		if(userid==null)
	 		{
	 			userid=new ArrayList<String>();
	 			userids.put(udrl.getDptid()+"", userid);
	 		}
	 		userid.add(udrl.getUserid()+"");
	  	 }
	 	
		 TreeHelper.generateDTree(systemdepttreemap,userids);
	 	// applicationContextHelper.servletContext.setAttribute("sendi_sys_deptment_tree", systemdepttreemap);
		
	}
	public void dptInit()
	{
		 
		 List datas=null;
	 
		if(this.reloadflag.equalsIgnoreCase("no")&&getSession().getAttribute(data_session_name)!=null)
		{
			datas=(List)getSession().getAttribute(data_session_name);
			//System.out.println("use session size"+datas.size());
		}
		else
		{
			addDptTosessin();
			datas=(List)getSession().getAttribute(data_session_name);
		}
		//this.sortObjectList(datas);
			writeJSONArray(datas);
		 
	}
	
	public void addDptTosessin()
	{
        	List datas=new ArrayList<Department>();;
          HashMap<String,DepartTreeNode> systemdepttreemap=null;
		  Object mt2=this.getServletContext().getAttribute("sendi_sys_deptment_tree");
		  String userid=this.getUserKeyId();
			if(mt2!=null)
		 	{
		  		systemdepttreemap=(HashMap<String,DepartTreeNode>)mt2;
		  	}
			ArrayList<DepartTreeNode> childpart=null;
			try
			{
				childpart=systemdepttreemap.get(this.clickleafid+"").dchild;
				for(DepartTreeNode d:childpart)
				{
					if(d.isPower(userid))
					{
						datas.add(d.f);
			 		}
					
				}
			}
			catch (Exception e) {
				 
			}
		
	    
		
		getSession().removeAttribute(this.data_session_name);
		getSession().setAttribute(data_session_name,datas);
 	}
	
 
   /*
    * 查询用户
    */
	public void querydepartment()
	{
		   try
		   {
			     Session session=serviceSupportImp.getDao().getSessionFactory().openSession();
			 	StringBuffer hql=new StringBuffer("from Department where 1=1 ");
				if(departname!=null&&departname.trim().length()>0)
				{
					hql.append(" and  departname like :departname ");
				}
			 	   Query query= session.createQuery(hql.toString());
				   if(departname!=null&&departname.trim().length()>0)
					{
					  query.setParameter("departname", "%"+departname+"%");
					}
				 
					    List datas=query.list();
					  //  System.out.println("query size"+datas.size());
				     	getSession().setAttribute(data_session_name,datas);	
				     	writeResponseText("{success:true,msg:'success',datasize:"+datas.size()+"}");
		   			}
		   catch (Exception e) {
			   writeResponseText("{success:false,msg:'failure'}");
				 
		}
		    
		
	}

 
	 public void addDepartment()
	 {
		 
	 	 
		 Department department=new Department();
		 department.setDepartarea(departarea);
		 department.setDepartcode(departcode);
		 department.setDepartname(departname);
		 department.setDepartstatus(departstatus);
		 department.setParentid(parentid);
		 department.setDeparttype(departtype);
		 department.setDepartdesc(departdesc);
		 
	  	try {
				serviceSupportImp.save(department);
			 	getSession().removeAttribute(data_session_name);
			 	reConstructDeptData();
				addDptTosessin();
				writeResponseText("{success:true,msg:'success'}");
		 	} catch (Exception e) {
				writeResponseText("{success:false,msg:'faild',errors:{"+e.getMessage()+"}}");
			  e.printStackTrace();
			}
	 }

	 
	 public void excutModifyQuerydpt()
		{
		//	System.out.println("excutModifyQuery...."+id);
			String hql="from Department where 1=1 and id="+this.id; 
			
			List datas=serviceSupportImp.findByHQL(hql);
		 
		 	//System.out.println("data size:"+datas.size());
		 	Department dpartment=(Department)datas.get(0);
			try {
				//System.out.println("{success:true,datas:"+JSONObject.fromObject(dpartment).toString()+"}");
			 	writeResponseText("{success:true,datas:"+JSONObject.fromObject(dpartment).toString()+"}");
			} catch (Exception e) {
		 	   writeResponseText("{success:false,msg:'faild',errors:{"+e.getMessage()+"}}");
			 	e.printStackTrace();
			}
			
		}
		public void excuteModifydpt()
		{
		 
			String hql="from Department where 1=1 and id="+this.id; 
			
			List datas=serviceSupportImp.findByHQL(hql);
			Department department=(Department)datas.get(0);
			 department.setDepartarea(departarea);
			 department.setDepartcode(departcode);
			 department.setDepartname(departname);
			 department.setDepartstatus(departstatus);
			 department.setParentid(parentid);
			 department.setDeparttype(departtype);
			 department.setDepartdesc(departdesc);
			 
		 	serviceSupportImp.update(department);
			
			getSession().removeAttribute(data_session_name);
			reConstructDeptData();
		    addDptTosessin();
			writeResponseText("{success:true,msg:'success'}"); 
		}
		
		public void excuteDeletedpt()
		{
		 //todo 这里还差一个递归算法进行删除，目前只删除到下一级的节点，再下一级的节点不能删除了
		  String hql="delete Department where id in ("+deleterecord+") or  parentid in ("+deleterecord+")";
		  Session session=serviceSupportImp.getDao().getSessionFactory().openSession();
		  session.beginTransaction();
		  session.createQuery(hql).executeUpdate();
		  session.getTransaction().commit();
		 reConstructDeptData();
		  addDptTosessin();
		 writeResponseText("{success:true,msg:'success'}"); 
		}
		
		
		///////关联用户
		
		/*
		 * 查询该机构所有已选择与其他还没有选择的用户
		 */
		public void querySltandUnSltUser()
		{
			 if(this.querytype.equals("querynoselectuser")) //查询还没有选择的用户
			 {
				   String sql="SELECT   sys_user.userName,  sys_user.id  FROM   sys_user where  sys_user.id NOT IN (SELECT user_dpt_relation.userid FROM user_dpt_relation WHERE user_dpt_relation.dptid ="+this.dptid+") ";
			       if(this.username!=null&&this.username.trim().length()>0)
			       {
			    	   sql+=" and user.userName like '%"+this.username+"%' ";
			       }
			       
			     Session session=this.serviceSupportImp.getDao().getSessionFactory().openSession();
			     List<com.sendi.system.bean.User> returelist=new ArrayList<com.sendi.system.bean.User>();
			    List querylist= session.createSQLQuery(sql).addScalar("userName",Hibernate.STRING).addScalar("id",Hibernate.INTEGER).list();
			  //  System.out.println("sql query list1 "+querylist.size());
			   for(Object o:querylist)
			   {
				    Object oarr[]=(Object [])o;
				    com.sendi.system.bean.User u=new com.sendi.system.bean.User();
				    u.setUsername(oarr[0].toString());
				    u.setUserid(Integer.parseInt(oarr[1].toString()));
			 	    returelist.add(u);
			   }
		 	   writeJSONArray(returelist);
		 	       
			 }
			 else
			 {
				   String sql="SELECT   sys_user.userName,  sys_user.id  FROM   sys_user where  sys_user.id    IN (SELECT user_dpt_relation.userid FROM user_dpt_relation WHERE user_dpt_relation.dptid ="+this.dptid+") ";
				      
			     Session session=this.serviceSupportImp.getDao().getSessionFactory().openSession();
			  
			    List<com.sendi.system.bean.User> returelist=new ArrayList<com.sendi.system.bean.User>();
			    List querylist= session.createSQLQuery(sql).addScalar("userName",Hibernate.STRING).addScalar("id",Hibernate.INTEGER).list();
			 //   System.out.println("sql query list2 "+querylist.size()); 
			   for(Object o:querylist)
			   {
				    Object oarr[]=(Object [])o;
				    com.sendi.system.bean.User u=new com.sendi.system.bean.User();
				    u.setUsername(oarr[0].toString());
				    u.setUserid(Integer.parseInt(oarr[1].toString()));
			 	    returelist.add(u);
			   }
		 	   writeJSONArray(returelist);
		 	 }
			
		}
	  /*
	   * 需要将用机构关系删除，然后再进行重新插入
	   */
		public void addUserToDepartment()
		{
			// System.out.println("itemselector:"+this.itemselector+" useroleid:"+this.dptid);
			 String sql="delete from user_dpt_relation  WHERE user_dpt_relation.dptid ="+this.dptid;
			 Connection con=this.serviceSupportImp.getDao().getSessionFactory().openSession().connection();
			 Statement state;
			try {
				state = con.createStatement();
				state.executeUpdate(sql);
			 	String sql2="insert into user_dpt_relation (userid,dptid) values (?,?)";
			 	if(this.itemselector!=null&&this.itemselector.trim().length()>0)
			 	{
			 		String a[]=this.itemselector.split(",");
			 		PreparedStatement psd=con.prepareStatement(sql2);
			 		for(String b:a)
				 	{
			 			psd.setInt(1,Integer.parseInt(b));
				 		psd.setInt(2,this.dptid);
				 		psd.addBatch();
				 	}
			 		psd.executeBatch();
			  	}
			 	
			 	
				
			} catch (SQLException e) {
				 
				e.printStackTrace();
			}
			finally
			{
				try {
					con.close();
				} catch (SQLException e) {
				 
					e.printStackTrace();
				}
			}
			reConstructDeptData();
			writeResponseText("{success:true,msg:'success'}"); 
		}
		
	public Integer getId() {
		return id;
	}



	public void setId(Integer id) {
		this.id = id;
	}
 
	public String getDeleterecord() {
		return deleterecord;
	}


	public void setDeleterecord(String deleterecord) {
		this.deleterecord = deleterecord;
	}

	public int getClickleafid() {
		return clickleafid;
	}

	public void setClickleafid(int clickleafid) {
		this.clickleafid = clickleafid;
	}

	public String getReloadflag() {
		return reloadflag;
	}

	public void setReloadflag(String reloadflag) {
		this.reloadflag = reloadflag;
	}

	public String getDepartcode() {
		return departcode;
	}

	public void setDepartcode(String departcode) {
		this.departcode = departcode;
	}

	public String getDepartname() {
		return departname;
	}

	public void setDepartname(String departname) {
		this.departname = departname;
	}

	public String getDeparttype() {
		return departtype;
	}

	public void setDeparttype(String departtype) {
		this.departtype = departtype;
	}

	public Integer getParentid() {
		return parentid;
	}

	public void setParentid(Integer parentid) {
		this.parentid = parentid;
	}

	public String getDepartarea() {
		return departarea;
	}

	public void setDepartarea(String departarea) {
		this.departarea = departarea;
	}

	public String getDepartstatus() {
		return departstatus;
	}

	public void setDepartstatus(String departstatus) {
		this.departstatus = departstatus;
	}

	public String getDepartdesc() {
		return departdesc;
	}

	public void setDepartdesc(String departdesc) {
		this.departdesc = departdesc;
	}

	public String getQuerytype() {
		return querytype;
	}

	public void setQuerytype(String querytype) {
		this.querytype = querytype;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getDptid() {
		return dptid;
	}

	public void setDptid(int dptid) {
		this.dptid = dptid;
	}

	public String getItemselector() {
		return itemselector;
	}

	public void setItemselector(String itemselector) {
		this.itemselector = itemselector;
	}

	 
}
